//
//  EBFile.m
//  UMDReader
//
//  Created by 张 霄鹤 on 10-2-1.
//  Copyright 2010 xhzhang. All rights reserved.
//

#import "EBFile.h"


@implementation EBFile

@synthesize chapters;

- (id)init{
	if(self = [super init]){
		header = [[EBHeader alloc] init];
		data = [[NSMutableData alloc] init];
		chapters = [[NSMutableArray alloc] init];
	}
	return self;
}

- (void)read:(BEDataInputStream *)din{
	NSInteger mag = [din readShort];
	if(mag == EBF_MAGIC){
		crypted = ([din read] == 1);
		NSInteger hl = [din readInt];
		NSInteger rlen = 0;
		char *buf = [din getCurrentBytesRefwithLength:hl retLength:&rlen];
		[header load:buf length:rlen needCrypt:crypted];
		// 数据部分
		hl = [din readInt];
		buf = [din getCurrentBytesRefwithLength:hl retLength:&rlen];
		[self loadData:buf length:rlen];
	}
}

- (void)loadData:(char *)buf length:(NSInteger)rlen{
	NSData *d = [[NSData alloc] initWithBytes:buf length:rlen];
	BEDataInputStream *din = [[BEDataInputStream alloc] initWithData:d];
	NSArray *ts = [header getTitles];
	NSArray *os = [header getOffsets];
	NSString *s1, *s2;
	NSInteger len = [ts count];
	EBChapter *ch;
	NSInteger offset;
	for (int i = 0; i < len; i++) {
		[din reset];
		s1 = [ts objectAtIndex:i];
		s2 = [os objectAtIndex:i];
		ch = [[[EBChapter alloc] init] autorelease];
		ch.title = s1;
		offset = [s2 intValue];
		[din skip:offset];
		[ch load:din];
		[chapters addObject:ch];
	}
	[din release];
	[d release];
}

- (NSString *)getTitle{
	NSString *ret = @"";
	if(header){
		ret = header.title;
	}
	return ret;
}

- (void)dealloc{
	[header release];
	[data release];
	[chapters release];
	[super dealloc];
}

@end
